import "whatwg-fetch"
import commonStore from '../store/commonStore'
const tokenPlugin = () => {
  if (commonStore.token) {
     return commonStore.token
  }
};
const API_ROOT = '';
const _req = (url,body,method)=>{
  fetch(url, {
    method: method,
    body: JSON.stringify(body),
    headers:{
      "Content-type":"application:/x-www-form-urlencoded:charset=UTF-8",
      "Token": tokenPlugin()
    },
  }).then(resp => {
    return resp;
  }).then((data) => {
    return data
  }).catch(error => {
    throw error;
  });
}
const requests = {
  get: url =>{
     return fetch(url, {
      method: 'GET',
    }).then((res) => {
          return res.json();
        })
        .then((data)=>{
          return JSON.stringify(data)
        })
        .catch((error)=>{
          throw error
        });
  },
  post: (url,body)=>{
     _req(API_ROOT+url,body,"POST")
  },
  delete:(url,body)=>{
    _req(API_ROOT+url,body,"DELETE")
  },
  put: (url,body)=>{
    _req(API_ROOT+url,body,"PUT")
  }
};

const Auth ={
  login:()=>{
     return requests.get("http://jsonplaceholder.typicode.com/posts").then((data)=>{
        return data;
    }).catch((e)=>{
      throw  e
     })
  },
  register:(username,email,password)=>{
    return requests.post("/register",{"username":username,"password":password,"email":email})
        .then((data)=>{
          return data;
        }).catch((e)=>{
          throw e;
        })
  }
}

export default {
  Auth
}


